package com.socialuni.common.user.sdk.domain;

import com.socialuni.common.user.sdk.manage.CommonUserAccountDOCreate;
import com.socialuni.common.user.sdk.manage.CommonUserAccountDOGet;
import com.socialuni.common.user.sdk.manage.CommonUserDOCreate;
import com.socialuni.common.user.sdk.manage.CommonUserDOGet;
import com.socialuni.uniapp.sdk.exception.UniSdkException;
import com.socialuni.uniapp.sdk.model.UniUnionIdRO;
import com.socialuni.uniapp.sdk.model.UniProviderLoginQO;
import com.socialuni.uniapp.sdk.utils.UniProviderUtil;
import com.socialuni.common.user.model.DO.CommonUserAccountDO;
import com.socialuni.common.user.model.DO.CommonUserDO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CommonUserDODomainCreate {
    @Resource
    CommonUserDOCreate uniUserDOCreate;
    @Resource
    CommonUserAccountDOGet uniUserAccountDOGet;
    @Resource
    CommonUserDOGet uniUserDOGet;
    @Resource
    CommonUserAccountDOCreate uniUserAccountDOCreate;

    //根据渠道登录信息获取user
    public CommonUserDO getOrCreate(UniProviderLoginQO loginQO) throws UniSdkException {

        UniUnionIdRO uniUnionIdRO = UniProviderUtil.getUnionIdRO(loginQO);
        if (uniUnionIdRO.hasError()){
            throw new UniSdkException("获取openId失败");
        }
        return getOrCreate(loginQO, uniUnionIdRO);
    }

    public CommonUserDO getOrCreate(UniProviderLoginQO loginQO, UniUnionIdRO uniUnionIdRO) throws UniSdkException {
        CommonUserAccountDO accountDO = uniUserAccountDOGet.getAccountByUnionId(loginQO, uniUnionIdRO);
        CommonUserDO socialUserDO;
        //如果已经注册过
        if (accountDO != null) {
            socialUserDO = uniUserDOGet.get(accountDO.getUserId());
        } else {
            socialUserDO = this.create(loginQO, uniUnionIdRO);
        }
        return socialUserDO;
    }

    public CommonUserDO create(UniProviderLoginQO loginQO, UniUnionIdRO uniUnionIdRO) throws UniSdkException {
        CommonUserDO socialUserDO = uniUserDOCreate.create(loginQO);
        uniUserAccountDOCreate.create(socialUserDO, loginQO, uniUnionIdRO);
        return socialUserDO;
    }
}
